<template>
  <div class="qa-wrapper">
    <div class="wrapper-header">
      <el-form :model="resetForm" ref="resetFormRef" label-width="120px">
        <el-form-item label="用户手机号" prop="phone">
          <el-input v-model="resetForm.phone" placeholder="请输入用户手机号"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetForm.newPassword" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetForm.confirmPassword" placeholder="请再次输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPassword">重置密码</el-button>
          <el-button v-if="resetFormRef" @click="resetFormRef.resetFields()">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <AdminKeyDialog ref="adminKeyDialog"></AdminKeyDialog>
  </div>
</template>
<style scoped>
@import '../style/applyReview.less';
</style>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import AdminKeyDialog from './AdminKeyDialog.vue'
import { useUserStore } from '@/stores/useStore'
import * as httpService from '@/services/apply.service'

const adminKeyDialog = ref<InstanceType<typeof AdminKeyDialog>>()
// 打开管理员密钥对话框并获取密钥
const openAdminKeyDialog = () => {
  if (!useUserStore().authInfo?.opCode) {
    adminKeyDialog.value?.show()
    return false
  } else {
    return true
  }
}
// 重置密码表单引用
const resetFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 重置密码表单数据
const resetForm = reactive({
  phone: '',
  newPassword: '',
  confirmPassword: '',
})
// 重置密码方法
const resetPassword = async () => {
  const hasOpCode = openAdminKeyDialog()
  if (!hasOpCode) {
    return
  }
  if (!resetForm.phone) {
    ElMessage.error('请输入用户手机号')
    return
  }
  if (!resetForm.newPassword) {
    ElMessage.error('请输入新密码')
    return
  }
  if (!resetForm.confirmPassword) {
    ElMessage.error('请确认密码')
    return
  }
  if (resetForm.newPassword !== resetForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  const opCode = useUserStore().authInfo?.opCode || ''
  const res = await httpService.resetUserPwd({ mobile: resetForm.phone, newPwd: resetForm.newPassword, opCode: opCode })
  if (res.data === 'ok') {
    ElMessage.success('密码重置成功')
    if (resetFormRef.value) {
        resetForm.newPassword = ''
        resetForm.confirmPassword = ''
    }
  } else {
    ElMessage.error('密码重置失败')
  }
}
onMounted(() => {})
</script>
